package com.atguigu.gmallpubliser.controller;

import com.atguigu.gmallpubliser.service.SugarService;
import com.atguigu.gmallpubliser.util.DateFormatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

//@Controller
@RestController
public class SugarController {

    @Autowired
    private SugarService sugarService;

    @RequestMapping("test")
    //@ResponseBody
    public String test1() {
        System.out.println("1111111111");
        return "aaaaaa";
    }

    public String test2() {
        System.out.println("1111111111");
        return "success";
    }

    @RequestMapping("gmv")
    public String getGmv(@RequestParam(value = "date", defaultValue = "0") String dt) {

        if ("0".equals(dt)) {
            dt = getToday();
        }

        //查询Doris数据
        BigDecimal gmv = sugarService.getGmv(dt);
        if (gmv == null) {
            gmv = new BigDecimal("0.0");
        }

        //封装JSON返回
        return "{\n" +
                "  \"status\": 0,\n" +
                "  \"msg\": \"\",\n" +
                "  \"data\": " + gmv + "\n" +
                "}";
    }

    @RequestMapping("tm")
    public String getGmvByTm(@RequestParam(value = "date", defaultValue = "0") String date,
                             @RequestParam(value = "limit", defaultValue = "5") int limit) {

        if ("0".equals(date)) {
            date = getToday();
        }

        //查询Doris数据 Map[(苹果->526411),(华为->512222)...]
        Map<String, BigDecimal> gmvByTm = sugarService.getGmvByTm(date, limit);
        Set<String> tmNames = gmvByTm.keySet();
        Collection<BigDecimal> gmvs = gmvByTm.values();

        //封装JSON并返回
        return "{\n" +
                "  \"status\": 0,\n" +
                "  \"msg\": \"\",\n" +
                "  \"data\": {\n" +
                "    \"categories\": [\"" + StringUtils.join(tmNames, "\",\"") + "\"],\n" +
                "    \"series\": [\n" +
                "      {\n" +
                "        \"name\": \"手机品牌\",\n" +
                "        \"data\": [" + StringUtils.join(gmvs, ",") + "]\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";
    }

    private String getToday() {
        return DateFormatUtil.toDate(System.currentTimeMillis());
    }

}
